package au.edu.utas.yu_qiao_group.luckyman.service;

import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;

import au.edu.utas.yu_qiao_group.luckyman.db.draws.DrawTable;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleDTO;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleDrawDTO;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleTable;
import au.edu.utas.yu_qiao_group.luckyman.db.tickets.TicketDTO;

public class RaffleService {

  public static ArrayList<RaffleDTO> retrieveAll (SQLiteDatabase db) {
    return RaffleTable.selectAll(db);
  }
  public static RaffleDrawDTO retreiveRaffleDrawByID (SQLiteDatabase db, long id) {
    RaffleDrawDTO result = null;
    try {
      result = DrawTable.joinDrawQueryByRaffleID(db, id);
    } catch (Exception e) {}
    return result;
  }
  public static boolean insertRaffle(SQLiteDatabase db, RaffleDTO r) {
    boolean result = false;
    r.setMTicketRemain(r.getMTicketTotal());
    db.beginTransaction();
    try {
      long rowId = RaffleTable.insert(db, r);
      r.setMRaffleID(rowId); // fill
      if (DrawService.insertDraw(db, r)) {
        db.setTransactionSuccessful();
        result = true;
      }
    } catch (android.database.sqlite.SQLiteConstraintException e) {
      System.out.print(e);
    } finally {
      db.endTransaction();
    }
    return result;
  }

  public static boolean updateRaffle(SQLiteDatabase db, RaffleDTO r) {
    boolean result = false;
    try {
      RaffleTable.update(db, r);
      result = true;
    } catch (android.database.sqlite.SQLiteConstraintException e) {
      System.out.print(e);
    }
    return result;
  }

  public static boolean updateRaffleTickets(SQLiteDatabase db, RaffleDTO r, int remain) {
    boolean result = false;
    if (r.getMTicketTotal() < remain) {
      return result;
    }
    r.setMTicketRemain(remain);
    try {
      RaffleTable.update(db, r);
      result = true;
    } catch (Exception e) {
      System.out.print(e);
    }
    return result;
  }

  public static boolean delRaffle(SQLiteDatabase db, RaffleDTO r) {
    boolean result = false;
    ArrayList<TicketDTO> relativeTickets = TicketService.retrieveAllByRaffleID(db, r.getMRaffleID());
    if (relativeTickets.size() > 0) {
      return false;
    }
    db.beginTransaction();
    try {
      RaffleTable.delete(db, r);
      if (DrawService.cancelDraw(db, r)) {
        db.setTransactionSuccessful();
        result = true;
      }
    } catch (Exception e) {
      System.out.print(e);
    } finally {
      db.endTransaction();
    }
    return result;
  }
}
